package xin.yangshuai.springsecurity03.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Component;
import xin.yangshuai.springsecurity03.entity.SpringSecurityUser;
import xin.yangshuai.springsecurity03.mapper.SpringSecurityUserMapper;

@Component
public class DatabaseUserDetailsManager implements UserDetailsManager {

    @Autowired
    private SpringSecurityUserMapper springSecurityUserMapper;

    @Override
    public void createUser(UserDetails user) {

    }

    @Override
    public void updateUser(UserDetails user) {

    }

    @Override
    public void deleteUser(String username) {

    }

    @Override
    public void changePassword(String oldPassword, String newPassword) {

    }

    @Override
    public boolean userExists(String username) {
        return false;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SpringSecurityUser springSecurityUser1 = springSecurityUserMapper.selectById("123");
        System.out.println(springSecurityUser1);

        LambdaQueryWrapper<SpringSecurityUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SpringSecurityUser::getUsername, username);
        SpringSecurityUser springSecurityUser = springSecurityUserMapper.selectOne(queryWrapper);

        if (springSecurityUser == null) {
            throw new UsernameNotFoundException(username);
        } else {
            UserDetails user = User.builder()
                    .username(springSecurityUser.getUsername())
                    .password(springSecurityUser.getPassword())
                    // 这里示例，权限手动添加
                    .authorities("USER_ADD", "USER_UPDATE", "USER_LIST").build();
            return user;
        }
    }
}
